package com.fansl.koala.quickdev.component.message.email;

import cn.hutool.core.util.RandomUtil;
import com.fansl.koala.quickdev.common.bean.entity.SendMailMessage;
import com.fansl.koala.quickdev.common.bean.po.SendMailMessagePo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;

/**
 * @author fansl
 * @Description: 注册消息模板
 * @date 2019/10/10 13:38
 */
@Slf4j
@Component
public class RegisterMessageTemplateExecutor implements EmailMessageTemplateExecutor {
    @Resource
    private TemplateEngine templateEngine;

    /**
     * 创建消息模板
     *
     * @param mailMessage 邮箱消息内容
     * @throws Exception 异常信息
     */
    @Override
    public SendMailMessage createMessageTemplate(SendMailMessagePo mailMessage) throws Exception {
        SendMailMessage sendMailMessage = new SendMailMessage();
        //收件人
        sendMailMessage.setReceiver(mailMessage.getReceiver());
        //生成验证码
        String code = generateVerCode();
        //返回内容
        sendMailMessage.setReturnContent(code);
        //邮件正文
        sendMailMessage.setContent(createContent(code));
        //邮件标题
        sendMailMessage.setSubject(createSubject(mailMessage));
        return sendMailMessage;
    }

    private String createContent(String verifyCode) {
        Context context = new Context();
        context.setVariable("verifyCode", verifyCode);
        return templateEngine.process("emailVerifyCode", context);
    }

    private String createSubject(SendMailMessagePo mailMessage) {
        return mailMessage.getEmailMessageType().getDescription() + "验证码";
    }

    /**
     * 生成验证码
     *
     * @return
     */
    private String generateVerCode() {
        return RandomUtil.randomNumbers(6);
    }

}
